package com.braveman.im.ui.activity.message;

import android.Manifest;
import android.content.Context;
import android.content.Intent;

import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.braveman.im.R;
import com.braveman.im.bean.JsonNewBean;
import com.braveman.im.bean.PicUpdateBean;
import com.braveman.im.bean.ReponseFileBean;
import com.braveman.im.bean.SendLoveNotifyBean;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.thread.CompressPhotoThread;
import com.braveman.im.ui.adapter.PhotoAdapter;
import com.braveman.im.ui.weiget.ButtonItem;
import com.braveman.im.ui.weiget.CustomPopwindow;
import com.braveman.im.ui.weiget.DialogUtils;
import com.braveman.im.ui.weiget.RecyclerItemClickListener;
import com.braveman.im.utils.GetJsonDataUtil;
import com.braveman.im.utils.PermissionUtils;
import com.braveman.im.utils.UtilsStyle;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.LogUtils;
import com.ht.baselibs.utils.UIUtils;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.vondear.rxtools.RxBarTool;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

public class SendLoveActivity extends BaseActivity {

    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private PhotoAdapter photoAdapter;
    private ArrayList<String> selectedPhotos = new ArrayList<>();
    private RecyclerView recyclerView;
    private QMUIRadiusImageView mIvIdentityCardFront;
    private QMUIRadiusImageView mIvIdentityCardContrary;
    private Thread thread;
    private static final String TAKE_PHOTO_PATH = "ht/jkm/photo/CARD_ICON.jpg";
    private static final String TAKE_PHOTO_PATH_CODE = "ht/jkm/photo/CARD_ICON_CODE.jpg";
    private static final int REQUEST_CODE_TAKE_PHOTO = 1;
    private static final int REQUEST_CAMERA_CODE = 2;
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 0;
    private static final int MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD = 1;
    private String picturePath;
    private int type = 0;
    private String picturePath1;
    private File file;
    private String indentityPathContrary;//身份证反面path
    private String indentityPathFront;//身份证正面path
    private EditText mEtActivitySendLoveTheme;
    private EditText mEtActivitySendLoveName;
    private EditText mEtActivitySendLoveDetails;
    private EditText mEtActivitySendLovePhone;
    private ButtonItem mBtiActivitySendLoveAddress;
    private EditText mEtActivitySendLoveAddressDetails;
    private RecyclerView mRecyclerView;
    private TextView mBtnActivitySendLove;
    private List<String> appLicationList = new ArrayList<>();

    private static final int REQUEST_CODE_PERMISSION_PHOTO_PREVIEW = 1;

    private JsonNewBean.ChildBeanX.ChildBean childBean = new JsonNewBean.ChildBeanX.ChildBean();
    private ArrayList<JsonNewBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>>> options3Items = new ArrayList<>();
    private String corpAddressId;
    private String corpAddressName;


    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {
        mTitleBarView.setTitleText("发布爱心").setLeftBtnIcon(R.mipmap.back_black).setOnLeftBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtils.finishActivity(SendLoveActivity.this);
            }
        });
    }

    @Override
    protected int initContentView() {
        UtilsStyle.setStatusBarMode(this, true);
        RxBarTool.FlymeSetStatusBarLightMode(getWindow(), true);
        RxBarTool.MIUISetStatusBarLightMode(getWindow(), true);
        return R.layout.activity_send_love;
    }

    @Override
    protected void initChildView() {
        recyclerView = findViewById(R.id.recycler_view);
        mIvIdentityCardFront = findViewById(R.id.iv_identity_card_front);
        mIvIdentityCardContrary = findViewById(R.id.iv_identity_card_contrary);
        mIvIdentityCardFront.setCircle(false);
        mIvIdentityCardContrary.setCircle(false);
        mEtActivitySendLoveTheme = findViewById(R.id.et_activity_send_love_theme);
        mEtActivitySendLoveName = findViewById(R.id.et_activity_send_love_name);
        mEtActivitySendLoveDetails = findViewById(R.id.et_activity_send_love_details);
        mEtActivitySendLovePhone = findViewById(R.id.et_activity_send_love_phone);
        mBtiActivitySendLoveAddress = findViewById(R.id.bti_activity_send_love_address);
        mEtActivitySendLoveAddressDetails = findViewById(R.id.et_activity_send_love_address_details);
        mRecyclerView = findViewById(R.id.recycler_view);
        mIvIdentityCardFront = findViewById(R.id.iv_identity_card_front);
        mIvIdentityCardContrary = findViewById(R.id.iv_identity_card_contrary);
        mBtnActivitySendLove = findViewById(R.id.btn_activity_send_love);

    }

    @Override
    protected void initChildData() {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }

    @Override
    protected void setChildViewListener() {
        mIvIdentityCardFront.setOnClickListener(this);
        mIvIdentityCardContrary.setOnClickListener(this);
        findViewById(R.id.btn_activity_send_love).setOnClickListener(this);
        findViewById(R.id.bti_activity_send_love_address).setOnClickListener(this);


        photoAdapter = new PhotoAdapter(this, selectedPhotos);

        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
        recyclerView.setAdapter(photoAdapter);


        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this,
                new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        if (photoAdapter.getItemViewType(position) == PhotoAdapter.TYPE_ADD) {
                            PhotoPicker.builder()
                                    .setPhotoCount(PhotoAdapter.MAX)
                                    .setShowCamera(true)
                                    .setPreviewEnabled(false)
                                    .setSelected(selectedPhotos)
                                    .start(SendLoveActivity.this);
                        } else {
                            PhotoPreview.builder()
                                    .setPhotos(selectedPhotos)
                                    .setCurrentItem(position)
                                    .start(SendLoveActivity.this);
                        }
                    }
                }));
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_identity_card_front:
                type = 0;
                try {
                    InputMethodManager im = (InputMethodManager) SendLoveActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(SendLoveActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture(type);
                    } else {
                        ActivityCompat.requestPermissions(SendLoveActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(SendLoveActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }
                break;
            case R.id.iv_identity_card_contrary:
                type = 1;
                try {
                    InputMethodManager im = (InputMethodManager) SendLoveActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(SendLoveActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture(type);
                    } else {
                        ActivityCompat.requestPermissions(SendLoveActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(SendLoveActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }
                break;
            case R.id.btn_activity_send_love:
                SendLoveNotifyBean sendLoveNotifyBean = new SendLoveNotifyBean();
                sendLoveNotifyBean.subject = mEtActivitySendLoveTheme.getText().toString().trim();
                sendLoveNotifyBean.contactName = mEtActivitySendLoveName.getText().toString().trim();
                sendLoveNotifyBean.contactPhone = mEtActivitySendLovePhone.getText().toString().trim();
                sendLoveNotifyBean.detail = mEtActivitySendLoveDetails.getText().toString().trim();
                sendLoveNotifyBean.detailedAddress = mEtActivitySendLoveAddressDetails.getText().toString().trim();
                sendLoveNotifyBean.regionId = corpAddressId;//地区id
                sendLoveNotifyBean.applicantPhotoList = new ArrayList<>();
                sendLoveNotifyBean.imageList = new ArrayList<>();
                sendLoveNotifyBean.imageList.addAll(appLicationList);
                sendLoveNotifyBean.applicantPhotoList.add(indentityPathFront);
                sendLoveNotifyBean.applicantPhotoList.add(indentityPathContrary);

                if (TextUtils.isEmpty(sendLoveNotifyBean.subject)) {
                    UIUtils.showToast("请输入爱心主题");
                    return;
                }
                if (TextUtils.isEmpty(sendLoveNotifyBean.contactName)) {
                    UIUtils.showToast("请输入受助人");
                    return;
                }
                if (TextUtils.isEmpty(sendLoveNotifyBean.contactPhone)) {
                    UIUtils.showToast("请输入爱心详情");
                    return;
                }
                if (TextUtils.isEmpty(sendLoveNotifyBean.regionId)) {
                    UIUtils.showToast("请选择地区");
                    return;
                }
                if (TextUtils.isEmpty(sendLoveNotifyBean.detailedAddress)) {
                    UIUtils.showToast("请输入详细地址");
                    return;
                }
                if (sendLoveNotifyBean.applicantPhotoList != null && sendLoveNotifyBean.applicantPhotoList.size() == 0) {
                    UIUtils.showToast("请上传证明图片");
                    return;
                }
                if (sendLoveNotifyBean.imageList != null && sendLoveNotifyBean.imageList.size() < 2) {
                    UIUtils.showToast("请上传证件图片");
                    return;
                }
                ApiManager.getApi().sendLoveNotify(sendLoveNotifyBean).enqueue(new NetCallBack<ReponseFileBean>() {
                    @Override
                    protected void onSuccess(Call<ReponseFileBean> call, Response<ReponseFileBean> response) {
                        if (response != null) {
                            UIUtils.showToast("发布爱心成功");
                            ActivityUtils.finishActivity(SendLoveActivity.this);
                        }
                    }
                });
                break;
            case R.id.bti_activity_send_love_address:
                mBtiActivitySendLoveAddress.tv_des.setText("");
                ShowFullPickerView(mBtiActivitySendLoveAddress);
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //                 选择照片
                case REQUEST_CODE_TAKE_PHOTO:
                    String filePath1 = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                    new CompressPhotoThread(mHandler, filePath1, 0).start();
                    toUpdata(filePath1, 0);
                    break;
                case REQUEST_CAMERA_CODE:
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    new CompressPhotoThread(mHandler, picturePath, 1).start();
                    toUpdata(picturePath, 0);

                    break;
                case REQUEST_CODE_TAKE_PHOTO + 10:
                    String filePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH_CODE;
                    new CompressPhotoThread(mHandler, filePath, 2).start();
                    toUpdata(filePath, 1);

                    break;
                //                 选择照片
                case REQUEST_CAMERA_CODE + 10:
                    Uri selectedImage1 = data.getData();
                    String[] filePathColumn1 = {MediaStore.Images.Media.DATA};
                    Cursor cursor1 = this.getContentResolver().query(selectedImage1,
                            filePathColumn1, null, null, null);
                    cursor1.moveToFirst();
                    int columnIndex1 = cursor1.getColumnIndex(filePathColumn1[0]);
                    picturePath1 = cursor1.getString(columnIndex1);
                    cursor1.close();
                    new CompressPhotoThread(mHandler, picturePath1, 3).start();
                    toUpdata(picturePath1, 0);
                    break;
            }

//            if (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE) {
            if (requestCode == PhotoPicker.REQUEST_CODE) {

                List<String> photos = null;
                selectedPhotos.clear();
                if (data != null) {
                    photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                    MultipartBody.Part[] part = new MultipartBody.Part[photos.size()];

                    if (photos != null && photos.size() > 0) {

                        for (int x = 0; x < photos.size(); x++) {

                            String path = photos.get(x);

                            file = new File(path);
                            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);

                            part[x] = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
                        }
                        showLoadingDialog();
                        ApiManager.getApi().uploadPicGroup("image", part)
                                .enqueue(new NetCallBack<List<PicUpdateBean>>() {
                                    @Override
                                    protected void onSuccess(Call<List<PicUpdateBean>> call, Response<List<PicUpdateBean>> response) {
                                        LogUtils.debug(response.body().toString());
                                        if (response != null) {
                                            UIUtils.showToast("图片上传成功");
                                            List<PicUpdateBean> picUpdateBeanList = response.body();
                                            if (picUpdateBeanList != null && picUpdateBeanList.size() > 0) {
                                                if (appLicationList.size() != 0) {
                                                    appLicationList.clear();
                                                }
                                                for (PicUpdateBean piv : picUpdateBeanList) {
                                                    appLicationList.add(piv.url);
                                                }

                                            }
                                        }
                                    }

                                    @Override
                                    protected void hiddenProgress() {
                                        hideLodingDialog();
                                    }
                                });
                    }

                }
                if (photos != null) {

                    selectedPhotos.addAll(photos);

                }
                photoAdapter.notifyDataSetChanged();
            } else if (requestCode == PhotoPreview.REQUEST_CODE) {
                List<String> photos = null;
                if (data != null) {
                    photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                }
                selectedPhotos.clear();

                if (photos != null) {

                    selectedPhotos.addAll(photos);
                }
                photoAdapter.notifyDataSetChanged();
            }
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture(type);
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takePicture(type);
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void takePicture(final int count) {
        DialogUtils.createPopwindow(this, "", "取消", new CustomPopwindow.OnBtnClickListener("拍照") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory(), count == 0 ? TAKE_PHOTO_PATH : TAKE_PHOTO_PATH_CODE);
                Uri data;
                // 判断版本大于等于7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
                    data = FileProvider.getUriForFile(SendLoveActivity.this, "com.braveman.im.fileprovider", file);
                    // 给目标应用一个临时授权
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    data = Uri.fromFile(file);
                }
                intent.putExtra(MediaStore.EXTRA_OUTPUT, data);
                SendLoveActivity.this.startActivityForResult(intent, count == 0 ? REQUEST_CODE_TAKE_PHOTO : REQUEST_CODE_TAKE_PHOTO + 10);


            }
        }, new CustomPopwindow.OnBtnClickListener("从相册选择") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {

                Intent i = new Intent(
                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, count == 0 ? REQUEST_CAMERA_CODE : REQUEST_CAMERA_CODE + 10);
            }
        }).showAtLocation(mTitleBarView, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 130);
    }

    private void toUpdata(String path, final int count) {
        File file = new File(path);
        final RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        showLoadingDialog();
        ApiManager.getApi().uploadPic("image", filePart).enqueue(new NetCallBack<List<PicUpdateBean>>() {


            @Override
            protected void onSuccess(Call<List<PicUpdateBean>> call, Response<List<PicUpdateBean>> response) {
                UIUtils.showToast("图片上传成功");
                PicUpdateBean picUpdateBean = response.body().get(0);
                if (count == 0) {
                    indentityPathFront = picUpdateBean.url;
                } else if (count == 1) {
                    indentityPathContrary = picUpdateBean.url;
                }
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });
    }

    private void ShowFullPickerView(final ButtonItem buttonItem) {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(SendLoveActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options3Items.get(options1).get(options2).get(options3).name;
                buttonItem.tv_des.setText(tx);
                buttonItem.iv_des.setVisibility(View.GONE);
                corpAddressId = options3Items.get(options1).get(options2).get(options3).id;
                corpAddressName = options3Items.get(options1).get(options2).get(options3).name;
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

//        /*pvOptions.setPicker(options1Items);//一级选择器

//        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(SendLoveActivity.this, "province_new.json");//获取assets目录下的json文件数据

        ArrayList<JsonNewBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<JsonNewBean.ChildBeanX.ChildBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).child.size(); c++) {//遍历该省份的所有城市
                JsonNewBean.ChildBeanX.ChildBean childBean = new JsonNewBean.ChildBeanX.ChildBean();
                childBean.name = jsonBean.get(i).child.get(c).name;
                childBean.id = jsonBean.get(i).child.get(c).id;
                CityList.add(childBean);//添加城市

                ArrayList<JsonNewBean.ChildBeanX.ChildBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).child.get(c).name == null
                        || jsonBean.get(i).child.get(c).child.size() == 0) {
                    City_AreaList.add(new JsonNewBean.ChildBeanX.ChildBean());
                } else {

                    for (int d = 0; d < jsonBean.get(i).child.get(c).child.size(); d++) {//该城市对应地区所有数据
                        JsonNewBean.ChildBeanX.ChildBean childBean1 = new JsonNewBean.ChildBeanX.ChildBean();
                        childBean1.name = jsonBean.get(i).child.get(c).child.get(d).name;
                        childBean1.id = jsonBean.get(i).child.get(c).child.get(d).id;
                        City_AreaList.add(childBean1);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonNewBean> parseData(String result) {//Gson 解析
        ArrayList<JsonNewBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonNewBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonNewBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        Toast.makeText(SendLoveActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    Toast.makeText(SendLoveActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(SendLoveActivity.this, "Parse Failed", Toast.LENGTH_SHORT).show();
                    break;

                case 200: //图片
                    int type = (int) msg.obj;
                    String path = "";
                    switch (type) {
                        case 0:
                            path = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                            Glide.with(SendLoveActivity.this)//
                                    .load(path)
                                    .into(mIvIdentityCardFront);
                            break;
                        case 1:
                            path = picturePath;
                            Glide.with(SendLoveActivity.this)//
                                    .load(path)
                                    .into(mIvIdentityCardFront);
                            break;
                        case 2:
                            path = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH_CODE;
                            Glide.with(SendLoveActivity.this)//
                                    .load(path)
                                    .into(mIvIdentityCardContrary);

                            break;
                        case 3:
                            path = picturePath1;
                            Glide.with(SendLoveActivity.this)//
                                    .load(path)
                                    .into(mIvIdentityCardContrary);
                            break;


                    }
            }
        }
    };


}

